package com.dakor.catalog;

import com.dakor.catalog.gui.CatalogForm;
import com.dakor.catalog.persistence.dao.IFilmDao;
import com.dakor.catalog.persistence.entity.Film;
import com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel;
import org.apache.log4j.Logger;

import javax.swing.*;
import java.io.File;
import java.io.FilenameFilter;
import java.util.LinkedList;
import java.util.List;

/**
 * .
 *
 * @author Korobeynikov Dmitry
 * @version 1.0
 */
public class BaseEntryPoint {
    private static final String PATH = "e:\\video\\fff";

    private static IFilmDao filmDao = Context.getBean(IFilmDao.class);

    public static void main(String[] args) {
        init();

        try {
            UIManager.setLookAndFeel(new NimbusLookAndFeel());
        } catch (Exception e) {
            e.printStackTrace();
        }
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                CatalogForm form = CatalogForm.getInstance();
                form.fillData(filmDao.selectAll());
                form.setVisible(true);
            }
        });
    }

    private static void init() {
        List<File> files = new LinkedList<File>();
        parseFiles(new File(PATH), files);

        filmDao.clear();
        for (File file : files) {
            Film film = new Film();
            film.setName(file.getName());
            filmDao.insert(film);
        }
    }

    /**
     * Scan dir and subdirs for files.
     * @param dir   - directory for scan
     * @param files - result files
     */
    private static void parseFiles(File dir, List<File> files) {
        for (File file : dir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name != null && (name.endsWith(".avi") || name.endsWith(".mpg")
                        || name.endsWith(".mkv"));
            }
        })) {
            if (file.isDirectory()) {
                parseFiles(file, files);
            } else {
                files.add(file);
            }
        }
    }

}
